<template>
  <div style="position: relative">
    <div class="content">
      <!-- <el-tabs type="border-card" class="eltabs">
        <el-tab-pane label="区域船舶"> -->
      <div class="flex-column">
        <div class="shipNum">
          <span>区域船舶数：{{ list.length }}</span>
          <el-button type="primary" size="small">导出</el-button>
        </div>

        <div>
          <div class="collBox">
            <div class="collItem" v-for="item in list" :key="item.trackId">
              {{ item.chineseName || item.name || item.mmsi }}
            </div>
          </div>
          <!-- <el-tabs v-model="activeName">
                <el-tab-pane name="1">
                  <span slot="label">
                    在航({{ sailList.length }})
                  </span>
                  <div class="collBox">
                    <div
                      class="collItem"
                      v-for="item in sailList"
                      :key="item.trackId"
                      @click="getShip(item)"
                    >
                      {{ item.name }}
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane name="2">
                  <span slot="label">
                    锚泊({{ moorList.length }})
                  </span>
                  <div class="collBox">
                    <div
                      class="collItem"
                      v-for="item in moorList"
                      :key="item.trackId"
                      @click="getShip(item)"
                    >
                      {{ item.name }}
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs> -->
        </div>
      </div>
      <div class="eBox" v-if="isShow">
        <div class="eBox_head">
          <span>船舶：{{ list.length }}艘</span>
          <img :src="guanbiIcon" alt="" @click="isShow = false" />
        </div>
        <div id="eone"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 声明全局对象
declare global {
  interface Window {
    map: any;
    T: any;
  }
}

import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import eventBus from '@/utils/eventBus';
import jingzhunIcon from '@/assets/images/jingzhun.png';
import guanbiIcon from '@/assets/images/guanbi.png';

// 定义全局变量
declare const window: Window & { T: any };
const T = window.T;

// 定义类型
interface ShipItem {
  trackId: string | number;
  chineseName?: string;
  name?: string;
  mmsi: string;
  lon: number;
  lat: number;
  cog: number;
  shipType: number;
  sog?: number;
}

// 响应式状态
const activeName = ref('1');
const isShow = ref(true);
const marker = ref<HTMLElement | null>(null);
const kcList = ref<ShipItem[]>([]); // 客船
const hcList = ref<ShipItem[]>([]); // 货船
const yhList = ref<ShipItem[]>([]); // 液化船
const gzList = ref<ShipItem[]>([]); // 工作船
const zyList = ref<ShipItem[]>([]); // 作业船
const tcList = ref<ShipItem[]>([]); // 拖船
const ycList = ref<ShipItem[]>([]); // 渔船
const qtList = ref<ShipItem[]>([]); // 其他
const bdycList = ref<ShipItem[]>([]); // 北斗渔船
const bdytList = ref<ShipItem[]>([]); // 北斗游艇
const bdxtList = ref<ShipItem[]>([]); // 北斗小艇
const sailList = ref<ShipItem[]>([]); // 在航的船
const moorList = ref<ShipItem[]>([]); // 锚泊的船
const loading = ref(false);
const list = ref<ShipItem[]>([]);

// 方法
const typeStatis = () => {
  kcList.value = [];
  hcList.value = [];
  zyList.value = [];
  tcList.value = [];
  ycList.value = [];
  qtList.value = [];
  
  loading.value = true;
  
  list.value.forEach((ele) => {
    let val = ele.shipType;
    if (val >= 60 && val < 70) {
      kcList.value.push(ele);
    } else if (val >= 70 && val < 75) {
      hcList.value.push(ele);
    } else if (val == 33) {
      zyList.value.push(ele);
    } else if (val == 52) {
      tcList.value.push(ele);
    } else if (val == 30) {
      ycList.value.push(ele);
    } else {
      qtList.value.push(ele);
    }
  });

  loading.value = false;
  setEcharts();
};

// 点击船，查看位置
const getShip = (val: ShipItem) => {
  if (!val || !window.map) return;

  if (marker.value && marker.value.parentNode) {
    let parent = marker.value.parentNode;
    parent.removeChild(marker.value);
  }

  const lng = val.lon;
  const lat = val.lat;
  
  if (window.map && window.map.panTo && T && T.LngLat) {
    window.map.panTo(new T.LngLat(lng, lat));

    let img = document.createElement("img");
    img.src = jingzhunIcon;
    let latlng = new T.LngLat(lng, lat);
    marker.value = document.createElement("div");
    img.style.width = "25px";
    img.style.height = "25px";
    img.style.transform = `rotate(${val.cog || 0}deg)`;
    marker.value.appendChild(img);
    marker.value.style.position = "absolute";
    
    if (window.map.getPanes() && window.map.getPanes().overlayPane) {
      window.map.getPanes().overlayPane.appendChild(marker.value);
      let pos = window.map.lngLatToLayerPoint(latlng);
      marker.value.style.top = pos.y - 10 + "px";
      marker.value.style.left = pos.x - 10 + "px";
      marker.value.style.zIndex = "1000";
    }
  }
};

const setEcharts = () => {
  const chart = document.getElementById("eone");
  if (!chart) return;
  
  try {
    const myChart = echarts.init(chart);
    let dataList = [];
    let colorList = [];
    
    if (kcList.value.length > 0) {
      dataList.push({ value: kcList.value.length, name: "客船" });
      colorList.push("#FF4C4C");
    }
    if (hcList.value.length > 0) {
      dataList.push({ value: hcList.value.length, name: "货船" });
      colorList.push("#FFE02F");
    }
    if (yhList.value.length > 0) {
      dataList.push({ value: yhList.value.length, name: "液化船" });
      colorList.push("#54D228");
    }
    if (gzList.value.length > 0) {
      dataList.push({ value: gzList.value.length, name: "工作船" });
      colorList.push("#2A92FF");
    }
    if (zyList.value.length > 0) {
      dataList.push({ value: zyList.value.length, name: "作业船" });
      colorList.push("#A03810");
    }
    if (tcList.value.length > 0) {
      dataList.push({ value: tcList.value.length, name: "拖船" });
      colorList.push("#B95EA4");
    }
    if (ycList.value.length > 0) {
      dataList.push({ value: ycList.value.length, name: "渔船" });
      colorList.push("#00BBF2");
    }
    if (qtList.value.length > 0) {
      dataList.push({ value: qtList.value.length, name: "其他" });
      colorList.push("#F46B43");
    }
    if (bdycList.value.length > 0) {
      dataList.push({ value: bdycList.value.length, name: "北斗渔船" });
      colorList.push("#A2CE59");
    }
    if (bdytList.value.length > 0) {
      dataList.push({ value: bdytList.value.length, name: "北斗游艇" });
      colorList.push("#EF59A0");
    }
    if (bdxtList.value.length > 0) {
      dataList.push({ value: bdxtList.value.length, name: "北斗小艇" });
      colorList.push("#286BB4");
    }
    
    const handleData: Record<string, any> = {};
    let sum = 0;
    
    // 求和
    dataList.forEach((item: any) => {
      sum += item.value;
    });
    
    // 数据处理
    dataList.forEach((item: any) => {
      handleData[item.name] = item;
      handleData[item.name].percentage = ((item.value / sum) * 100).toFixed(1) + "%";
    });

    let option = {
      legend: {
        show: true,
        icon: "circle",
        right: "3%",
        left: "center",
        top: "5%",
        itemWidth: 10,
        itemStyle: {
          borderColor: "none",
        },
        textStyle: {
          color: "#ffffff",
        },
      },
      tooltip: {
        trigger: "item",
      },
      series: [
        {
          type: "pie",
          color: colorList,
          radius: "90%",
          left: "center",
          top: "3%",
          data: dataList,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 30,
          },
          label: {
            width: 100,
            fontSize: 12,
          },
          itemStyle: {
            borderColor: "#fff",
          },
        },
      ],
    };
    
    if (myChart && typeof myChart.setOption === 'function') {
      myChart.setOption(option);
    }
  } catch (error) {
    console.error("Error initializing chart:", error);
  }
};

// 设置事件监听
const setupEventListener = () => {
  eventBus.on("renewRegShip", () => {
    let info = localStorage.getItem("regShipInfo");
    if (info) {
      list.value = JSON.parse(info);
    }
  });
};

// 移除事件监听
const removeEventListener = () => {
  eventBus.off("renewRegShip");
  eventBus.emit("closeReg");
};

// 生命周期钩子
onMounted(() => {
  isShow.value = true;
  let info = localStorage.getItem("regShipInfo");
  if (info) {
    list.value = JSON.parse(info);
  }
  
  // 移除已有的事件监听
  eventBus.off("renewRegShip");
  
  // 设置新的事件监听
  setupEventListener();
  
  // 执行类型统计
  typeStatis();
});

// 组件卸载前执行清理
onBeforeUnmount(() => {
  removeEventListener();
});
</script>

<style scoped>
.content {
  /* width: 350px; */
  height: 100%;
  /* background: rgba(0, 0, 0, 0.5); */
  position: relative;
  /* right: 0;
  top: 60px;
  z-index: 99999; */
  /* display: flex;
  flex-direction: row; */
}

.eltabs {
  height: 100%;
  width: 380px;
}

.flex-column {
  display: flex;
  flex-direction: column;
}

.flex-row {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  font-size: 16px;
  color: #409eff;
}

.el-icon-circle-close {
  font-size: 22px;
}

/* .content-txt1 {
  font-size: 14px;
  color: #409eff;
} */

.line {
  width: 100%;
  height: 1px;
  margin: 10px auto;
  background: #d5d5d5;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
  color: #4386c6;
}

.custom-tree-node-label {
  display: block;
  width: 125px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.shipNum {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 20px 0;
}

.collBox {
  height: 650px;
  overflow: auto;
}

.collItem:hover {
  cursor: pointer;
}

.collItem {
  color: #409eff;
  margin-bottom: 10px;
}

.eBox {
  width: 350px;
  /* height: 350px; */
  position: fixed;
  bottom: 0;
  /* background-color: #454a6c; */
  background-color: rgba(31, 63, 130, 0.8) !important;
  right: 350px;
  color: #ffffff;
}

.eBox_head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 40px;
}

.eBox_head>img {
  width: 20px;
  height: 20px;
}

.eBox_head>img:hover {
  cursor: pointer;
}

#eone {
  height: 400px;
}

.elLabel {
  position: relative;
}

.elLabel_num {
  position: absolute;
  right: -10%;
  top: -30px;
  height: 30px;
  padding: 0 10px;
  background: #f56c6c;
  border-radius: 10px;
  z-index: 1000;
}

::-webkit-scrollbar {
  width: 4px;
  height: 10px;
  background-color: #f5f5f5;
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  background-color: #f5f5f5;
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #4376ec;
}
</style>

<style scoped src="@/assets/datePark.css"></style>